package com.zhang.yunfu_norevocation.controller;

import com.ccsp.sdk.crypto.CryptoException;
import com.zhang.yunfu_norevocation.comm.Utils.NoRevocationUtils;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zhang.bingmei_incomeexpenditure.entity.commom.R;
import com.zhang.yunfu_norevocation.entity.dto.InquiryPrescriptionDO;
import com.zhang.yunfu_norevocation.mapper.InquiryPrescriptionNoMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zsj
 * @description 添加不可否认性测试
 * @createDate 2025/11/7 09:17
 * @Entity com.dxih.inquiry.biz.rest.entity.
 */
/**
 * @author zsj
 * @description 不可否认性操作控制器（配合NoRevocationUtils）
 * @createDate 2025/11/7 09:17
 */
@RestController
//@Api(tags = "不可否认性操作")
@Slf4j
@RequestMapping("/noRevocat")
@RequiredArgsConstructor
public class IPNoRevocationController {
    @Resource
    private InquiryPrescriptionNoMapper prescriptionMapper;

    // 批量为处方添加不可否认性
    @ApiOperation("批量添加不可否认性")
    @ApiOperationSupport(author = "zsj")
    @RequestMapping("/addData")
    @Transactional(rollbackFor = Exception.class)
    public R addNoRevocationData() {
        List<InquiryPrescriptionDO> list = prescriptionMapper.selectList(null);
        if (list.isEmpty()) {
            return R.error(1, "查询不到处方数据");
        }

        AtomicInteger successCount = new AtomicInteger(); // 成功添加数量
        AtomicInteger failCount = new AtomicInteger();    // 失败数量

        list.forEach(tmp -> {
            try {
                boolean addSuccess = NoRevocationUtils.addNotDeniable(tmp);
                if (addSuccess) {
                    int updateRows = prescriptionMapper.updateById(tmp);
                    if (updateRows > 0) {
                        successCount.incrementAndGet();
                        log.info("【不可否认性添加】成功，处方编号：{}", tmp.getPrescriptNo());
                    } else {
                        failCount.incrementAndGet();
                        log.error("【不可否认性添加】数据库更新失败，处方编号：{}", tmp.getPrescriptNo());
                        throw new RuntimeException("数据库更新失败，触发回滚"); // 失败回滚
                    }
                } else {
                    failCount.incrementAndGet();
                    log.error("【不可否认性添加】工具类处理失败，处方编号：{}", tmp.getPrescriptNo());
                }
            } catch (CryptoException | IOException e) {
                failCount.incrementAndGet();
                log.error("【不可否认性添加】异常，处方编号：{}", tmp.getPrescriptNo(), e);
                throw new RuntimeException("添加异常，触发回滚", e); // 异常回滚
            }
        });

        return R.ok("添加完成",
                String.format("总数量：%d，成功：%d，失败：%d",
                        list.size(), successCount.get(), failCount.get()));
    }

    // 批量校验处方不可否认性
    @ApiOperation("批量校验不可否认性")
    @ApiOperationSupport(author = "zsj")
    @RequestMapping("/checkData")
    public R checkNoRevocationData() {
        List<InquiryPrescriptionDO> list = prescriptionMapper.selectList(null);
        if (list.isEmpty()) {
            return R.error(1, "查询不到处方数据");
        }

        AtomicInteger passCount = new AtomicInteger(); // 校验通过数量
        List<String> errorPrescriptNos = new ArrayList<>(); // 失败处方编号

        list.forEach(tmpDO -> {
            try {
                boolean checkPass = NoRevocationUtils.checkNotDeniable(tmpDO);
                if (checkPass) {
                    passCount.incrementAndGet();
                } else {
                    errorPrescriptNos.add(tmpDO.getPrescriptNo());
                }
            } catch (CryptoException e) {
                errorPrescriptNos.add(tmpDO.getPrescriptNo());
                log.error("【不可否认性校验】异常，处方编号：{}", tmpDO.getPrescriptNo(), e);
            } catch (Exception e) { // 捕获工具类未处理的其他异常
                errorPrescriptNos.add(tmpDO.getPrescriptNo());
                log.error("【不可否认性校验】未知异常，处方编号：{}", tmpDO.getPrescriptNo(), e);
            }
        });

        // 校验失败的处方，批量更新状态为-1
        if (!errorPrescriptNos.isEmpty()) {
            int updateRows = prescriptionMapper.batchUpdateStatusByPrescriptNo(errorPrescriptNos);
            log.error("【不可否认性校验】失败处方数量：{}，已更新状态为-1的数量：{}，失败处方编号：{}",
                    errorPrescriptNos.size(), updateRows, errorPrescriptNos);
        }

        return R.ok("校验完成",
                String.format("总数量：%d，通过：%d，失败：%d",
                        list.size(), passCount.get(), errorPrescriptNos.size()));
    }
}

